using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Xml.Linq;
using Drifter.Tools;
using System.IO;

namespace Drifter.Core
{


    public class FieldList : List<FieldDef>
    {



        //public override string ToString()
        //{

        //    StringBuilder sb = new StringBuilder();

        //    sb.Append("\r\n");

        //    foreach (Field field in this)
        //    {
        //        sb.Append(field.ToString());
        //        sb.Append("\r\n");
        //    }
        //    return sb.ToString();
        //}

        public void LoadFromFile(string path)
        {
            string xml = File.ReadAllText(path);
            XElement element = XElement.Parse(xml);
            Load(element);
        }

        public void Load(string xml)
        {
            XElement element = XElement.Parse(xml);
            Load(element);
        }


        public void Load(XElement element)
        {
            IEnumerable<XElement> root = element.Elements("field");

            var fieldDefs = from e in root
                            select new FieldDef()
                            {
                                Name = e.AttributeValue<string>("name"),
                                Source = e.AttributeValue<string>("source"),
                                Pos = e.AttributeValue<int?>("pos"),
                                Length = e.AttributeValue<int?>("length"),
                                Enabled = e.AttributeValue<bool>("enabled"),
                                Flexible = e.AttributeValue<bool>("flexible")
                            };

            foreach (var fieldDef in fieldDefs)
            {
                this.Add(fieldDef);
            }
        }


    }
}
